package com.demo.youxuanmall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Address;
import com.demo.youxuanmall.entity.Order;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.AddressService;
import com.demo.youxuanmall.service.FileService;
import com.demo.youxuanmall.service.OrderService;
import com.demo.youxuanmall.service.SystemSettingService;
import com.demo.youxuanmall.service.UserService;
import javax.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户个人中心控制器
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserProfileController extends BaseController {

    private final UserService userService;
    private final FileService fileService;
    private final AddressService addressService;
    private final OrderService orderService;

    public UserProfileController(SystemSettingService systemSettingService, 
                               UserService userService,
                               FileService fileService,
                               AddressService addressService,
                               OrderService orderService) {
        super(systemSettingService);
        this.userService = userService;
        this.fileService = fileService;
        this.addressService = addressService;
        this.orderService = orderService;
    }

    /**
     * 个人中心首页
     */
    @GetMapping("")
    public String profile(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 查询最新的几条订单
        List<Order> recentOrders = orderService.getRecentOrders(user.getId(), 5);
        model.addAttribute("recentOrders", recentOrders);
        model.addAttribute("user", user);
        
        return "user/profile";
    }

    /**
     * 修改个人信息
     */
    @GetMapping("/edit")
    public String editProfile(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        model.addAttribute("user", user);
        return "user/edit_profile";
    }

    /**
     * 保存个人信息
     */
    @PostMapping("/update")
    @ResponseBody
    public Result<User> updateProfile(@RequestBody User user, HttpSession session) {
        User sessionUser = (User) session.getAttribute("user");
        if (sessionUser == null) {
            return Result.error("请先登录");
        }
        
        // 只允许修改自己的信息
        user.setId(sessionUser.getId());
        return userService.updateProfile(user, session);
    }

    /**
     * 修改密码页面
     */
    @GetMapping("/password")
    public String passwordPage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        return "user/change_password";
    }

    /**
     * 修改密码操作
     */
    @PostMapping("/password")
    @ResponseBody
    public Result<?> updatePassword(@RequestBody User user, HttpSession session) {
        User sessionUser = (User) session.getAttribute("user");
        if (sessionUser == null) {
            return Result.error("请先登录");
        }
        
        // 只允许修改自己的密码
        user.setId(sessionUser.getId());
        return userService.updatePassword(user, session);
    }

    /**
     * 我的订单页面
     */
    @GetMapping("/orders")
    public String myOrders(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        List<Order> orders = orderService.getUserOrders(user.getId());
        model.addAttribute("orders", orders);
        
        return "user/orders";
    }

    /**
     * 地址管理页面
     */
    @GetMapping("/addresses")
    public String addresses(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        List<Address> addresses = addressService.getUserAddresses(user.getId());
        model.addAttribute("addresses", addresses);
        
        return "user/addresses";
    }

    @GetMapping("/profile")
    public String userProfile(Model model, HttpSession session,
                            @RequestParam(required = false) String active,
                            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                            @RequestParam(required = false, defaultValue = "5") Integer pageSize,
                            @RequestParam(required = false) Integer status) {
        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 校验分页参数合理性
        if (pageNum <= 0) {
            pageNum = 1;
        }
        
        if (pageSize <= 0 || pageSize > 20) {
            pageSize = 5;
        }
        
        try {
            // 更新用户信息
        User latestUser = userService.getByUsername(user.getUsername());
            if (latestUser == null) {
                log.error("无法获取用户[{}]的最新信息", user.getUsername());
                return "redirect:/login";
            }
            
            // 更新session
        session.setAttribute("user", latestUser);
            
            // 设置基本属性
        model.addAttribute("user", latestUser);
        model.addAttribute("active", active != null ? active : "profile");

            // 按需加载数据
            if ("orders".equals(active)) {
                // 使用service层查询订单
                try {
                Result<Page<Order>> result;
                if (status != null) {
                        result = orderService.listUserOrdersByStatus(latestUser.getId(), status, pageNum, pageSize);
                } else {
                        result = orderService.listUserOrders(latestUser.getId(), pageNum, pageSize);
                }
                
                if (result.getCode() == 0 && result.getData() != null) {
                    model.addAttribute("orderPage", result.getData());
                    model.addAttribute("status", status);
                } else {
                    model.addAttribute("orderError", result.getMsg());
                    }
                } catch (Exception e) {
                    log.error("查询订单列表异常: userId={}, active={}, status={}", latestUser.getId(), active, status, e);
                    model.addAttribute("orderError", "查询订单失败，系统繁忙，请稍后再试: " + e.getMessage());
                }
            }
            else if ("address".equals(active)) {
                // 地址管理
                List<Address> addresses = addressService.getUserAddresses(latestUser.getId());
                model.addAttribute("addresses", addresses);
        }

        return "user/profile";
        } catch (Exception e) {
            log.error("加载个人中心页面出错", e);
            model.addAttribute("error", "加载失败，请稍后再试");
            return "user/profile";
        }
    }

    @PostMapping("/profile/update")
    public String updateProfile(
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Integer gender,
            @RequestParam(required = false) MultipartFile avatar,
            HttpSession session) {
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        try {
            // 获取最新的用户信息
            User latestUser = userService.getByUsername(user.getUsername());
            
            // 更新用户信息
            latestUser.setNickname(nickname);
            latestUser.setPhone(phone);
            latestUser.setEmail(email);
            latestUser.setGender(gender);

            // 处理头像上传
            if (avatar != null && !avatar.isEmpty()) {
                String avatarUrl = fileService.uploadAvatar(avatar);
                if (avatarUrl != null) {
                    // 删除旧头像
                    if (latestUser.getAvatar() != null) {
                        fileService.deleteFile(latestUser.getAvatar());
                    }
                    latestUser.setAvatar(avatarUrl);
                }
            }

            // 更新用户信息
            userService.updateUserInfo(latestUser);
            
            // 更新session中的用户信息
            session.setAttribute("user", latestUser);
            
            log.info("用户信息更新成功: {}", latestUser.getUsername());
            return "redirect:/user/profile?success=true";
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return "redirect:/user/profile?error=true";
        }
    }
    
    /**
     * 确认收货
     */
    @PostMapping("/order/confirm")
    @ResponseBody
    public Result<Void> confirmReceived(@RequestParam String orderNo, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        try {
            log.info("用户[{}]确认收货: orderNo={}", user.getUsername(), orderNo);
            Result<Void> result = orderService.confirmOrder(user.getId(), orderNo);
            if (result.getCode() == 0) {
                log.info("确认收货成功: orderNo={}", orderNo);
            } else {
                log.warn("确认收货失败: orderNo={}, message={}", orderNo, result.getMsg());
            }
            return result;
        } catch (Exception e) {
            log.error("确认收货异常: orderNo={}", orderNo, e);
            return Result.error("确认收货失败: " + e.getMessage());
        }
    }
} 